package org.fastsyncer.rest.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.constant.ConnectorConstant;
import org.fastsyncer.common.entity.DatabaseConfig;
import org.fastsyncer.common.entity.LdapConfig;
import org.fastsyncer.common.entity.RedisConfig;
import org.fastsyncer.common.entity.RestResult;
import org.fastsyncer.common.entity.WebServiceConfig;
import org.fastsyncer.common.util.JsonUtil;
import org.fastsyncer.core.service.ConnectorService;
import org.fastsyncer.core.service.ManagerService;
import org.fastsyncer.core.service.PluginService;
import org.fastsyncer.rest.common.ThridpartAppHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/driver")
public class DriverController {

	private static final Logger logger = LoggerFactory.getLogger(DriverController.class);

	@Autowired
	private ManagerService manager;
	
    @Autowired
    private ConnectorService connector;
	
    @Autowired
    private PluginService plugin;
    
	@RequestMapping("/page/{opr}")
	public String driverAdd(HttpServletRequest request, ModelMap model, @PathVariable("opr") String opr, @RequestParam(value = "driverId", required = false) String driverId) {
		if (!StringUtils.isBlank(driverId)) {
			try {
				Object driver = manager.getDriver(driverId);
				model.addAttribute("dirver", driver);
				model.addAttribute("dirverJson", JsonUtil.objToJson(driver));
			} catch (Exception e) {
				logger.error(e.getLocalizedMessage(), e.getClass());
			}
		}
		
		//如果是新增请求
		if("driverAdd".equals(opr)){
			ThridpartAppHandler.checkSessionAppid(request);
		}
		return "driver/" + opr;
	}

	private RestResult getBaseInfoConnector(String connectorType, Object config){
	    try {
            return RestResult.restSuccess(connector.getBaseInfoConnector(connectorType, config));
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail("配置失败, 请检查参数.");
        }
	}
	
	/**
     * 获取连接器元信息
     * @param response
     * @param type 连接器类型
     * @param config 连接器配置
     * @return 连接器元信息
     */
    @RequestMapping(value = "/getMysqlConnector", method = RequestMethod.POST)
    @ResponseBody
    public RestResult getMysqlConnector(DatabaseConfig config) {
        return getBaseInfoConnector(ConnectorConstant.MYSQL_CONNECTOR, config);
    }
    
    @RequestMapping(value = "/getOracleConnector", method = RequestMethod.POST)
    @ResponseBody
    public RestResult getOracleConnector(DatabaseConfig config) {
        return getBaseInfoConnector(ConnectorConstant.ORACLE_CONNECTOR, config);
    }
    
    @RequestMapping(value = "/getSqlMysqlConnector", method = RequestMethod.POST)
    @ResponseBody
    public RestResult getSqlMysqlConnector(DatabaseConfig config) {
        return getBaseInfoConnector(ConnectorConstant.SQL_MYSQL_CONNECTOR, config);
    }
    
    @RequestMapping(value = "/getSqlOracleConnector", method = RequestMethod.POST)
    @ResponseBody
    public RestResult getSqlOracleConnector(DatabaseConfig config) {
        return getBaseInfoConnector(ConnectorConstant.SQL_ORACLE_CONNECTOR, config);
    }
    
    @RequestMapping(value = "/getSqlServerConnector", method = RequestMethod.POST)
    @ResponseBody
    public RestResult getSqlServerConnector(DatabaseConfig config) {
        return getBaseInfoConnector(ConnectorConstant.SQLSERVER_CONNECTOR, config);
    }
    
    @RequestMapping(value = "/getWebserviceConnector", method = RequestMethod.POST)
    @ResponseBody
    public RestResult getWebserviceConnector(WebServiceConfig config) {
        return getBaseInfoConnector(ConnectorConstant.WS_CONNECTOR, config);
    }
    
    @RequestMapping(value = "/getLdapConnector", method = RequestMethod.POST)
    @ResponseBody
    public RestResult getLdapConnector(@RequestParam(value = "json") String json) {
        try {
            JSONObject obj = new JSONObject(json);
            JSONArray list = obj.getJSONArray("extendObjects");
            int len = list.length();
            ArrayList<String> extendObjects = new ArrayList<String>(len);
            for (int i = 0; i < len; i++) {
                extendObjects.add(list.getString(i));
            }
            obj.remove("extendObjects");
            obj.remove("connector");
            obj.remove("name");
            LdapConfig config = JsonUtil.jsonToObj(obj.toString(), LdapConfig.class);
            config.setExtendObjects(extendObjects);
            return getBaseInfoConnector(ConnectorConstant.LDAP_CONNECTOR, config);
        } catch (JSONException e) {
            logger.error("", e.getLocalizedMessage());
        }
        return null;
    }
    
    @RequestMapping(value = "/getRedisConnector", method = RequestMethod.POST)
    @ResponseBody
    public RestResult getRedisConnector(RedisConfig config) {
        return getBaseInfoConnector(ConnectorConstant.REDIS_CONNECTOR, config);
    }
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public RestResult add(HttpServletRequest request, @RequestParam(value = "mapping") String mapping) {
		try {
			logger.info(mapping);
			if (StringUtils.isBlank(mapping)) {
				throw new NullPointerException("mapping参数不能为空！");
			}
			return RestResult.restSuccess(manager.add(mapping));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public RestResult update(HttpServletResponse response, @RequestParam(value = "mapping") String mapping) {
		try {
			logger.info(mapping);
			if (StringUtils.isBlank(mapping)) {
				throw new NullPointerException("mapping参数不能为空！");
			}
			return RestResult.restSuccess(manager.update(mapping));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}
	
	@RequestMapping(value = "/enable", method = RequestMethod.POST)
	@ResponseBody
	public RestResult enable(HttpServletResponse response, @RequestParam(value = "driverId") String driverId) {
		try {
			if (StringUtils.isBlank(driverId)) {
				throw new NullPointerException("name参数不能为空！");
			}
			return RestResult.restSuccess(manager.enable(driverId));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}
	
	@RequestMapping(value = "/disable", method = RequestMethod.POST)
	@ResponseBody
	public RestResult disable(HttpServletResponse response, @RequestParam(value = "driverId") String driverId) {
		try {
			if (StringUtils.isBlank(driverId)) {
				throw new NullPointerException("name参数不能为空！");
			}
			return RestResult.restSuccess(manager.disable(driverId));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}

	@RequestMapping(value = "/start", method = RequestMethod.POST)
	@ResponseBody
	public RestResult start(HttpServletResponse response, @RequestParam(value = "driverId") String driverId) {
		try {
			if (StringUtils.isBlank(driverId)) {
				throw new NullPointerException("参数不能为空！");
			}
			return RestResult.restSuccess(manager.start(driverId));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}
	
	@RequestMapping(value = "/stop", method = RequestMethod.POST)
	@ResponseBody
	public RestResult stop(HttpServletResponse response, @RequestParam(value = "driverId") String id) {
		try {
			if (StringUtils.isBlank(id)) {
				throw new NullPointerException("参数不能为空！");
			}
			return RestResult.restSuccess(manager.stop(id));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public RestResult delete(HttpServletResponse response, @RequestParam(value = "driverId") String driverId) {
		try {
			if (StringUtils.isBlank(driverId)) {
				throw new NullPointerException("参数不能为空！");
			}
			return RestResult.restSuccess(manager.delete(driverId));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}
	
	@RequestMapping(value = "/getPlugins", method = RequestMethod.POST)
    @ResponseBody
    public RestResult getPlugins(HttpServletResponse response) {
        try {
            return RestResult.restSuccess(plugin.getPlugins());
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail(e.getLocalizedMessage());
        }
    }

}
